from fastapi import APIRouter, Depends, HTTPException, status, Response
from sqlalchemy.orm import Session
from typing import List
import requests
import json
from datetime import datetime
from db import get_db
from api.routes.auth import get_current_user
from models.user import User
from models.medical_history import MedicalHistory
from schemas.medical_history import MedicalHistoryCreate, MedicalHistoryOut
from sqlalchemy import func

# ✅ 只保留一个 router，统一 prefix

router = APIRouter(tags=["病史"])


@router.get("/", response_model=List[MedicalHistoryOut])
def list_medical_history(
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的所有历史对话（按创建时间倒序）"""
    return (
        db.query(MedicalHistory)
        .filter(MedicalHistory.user_id == current_user.id)
        .order_by(MedicalHistory.createdAt.desc())
        .offset(skip)
        .limit(limit)
        .all()
    )


@router.get("/{history_id}", response_model=MedicalHistoryOut)
def get_medical_history(
    history_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取单条对话记录详情"""
    history = db.query(MedicalHistory).filter(
        MedicalHistory.id == history_id,
        MedicalHistory.user_id == current_user.id
    ).first()
    if not history:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="对话记录不存在"
        )
    return history


@router.post("/", response_model=MedicalHistoryOut)
def create_medical_history(
    data: MedicalHistoryCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建新的对话记录（前端传多轮对话数组的JSON字符串）"""
    try:
        json.loads(data.content)
    except json.JSONDecodeError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="content必须是有效的JSON字符串"
        )

    history = MedicalHistory(
        user_id=current_user.id,
        title=data.title,
        content=data.content
    )
    db.add(history)
    db.commit()
    db.refresh(history)
    return history


@router.put("/{history_id}", response_model=MedicalHistoryOut)
def update_medical_history(
    history_id: int,
    data: MedicalHistoryCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新对话记录（用于多轮对话追加消息后更新）"""
    history = db.query(MedicalHistory).filter(
        MedicalHistory.id == history_id,
        MedicalHistory.user_id == current_user.id
    ).first()
    if not history:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="对话记录不存在"
        )

    try:
        json.loads(data.content)
    except json.JSONDecodeError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="content必须是有效的JSON字符串"
        )

    history.title = data.title
    history.content = data.content
    history.updatedAt = func.now()  # 更新时间戳
    db.commit()
    db.refresh(history)
    return history


@router.delete("/{history_id}")
def delete_medical_history(
    history_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除对话记录"""
    history = db.query(MedicalHistory).filter(
        MedicalHistory.id == history_id,
        MedicalHistory.user_id == current_user.id
    ).first()
    if not history:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="对话记录不存在"
        )

    db.delete(history)
    db.commit()
    return {"detail": "对话记录已成功删除"}


@router.post("/query-disease/stream")
def stream_disease_query(
    query: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """调用AI接口进行疾病查询（流式响应），并自动保存为对话记录"""
    try:
        prompt = f"""
        请详细回答关于"{query}"的医疗问题，包括：
        1. 疾病概述
        2. 主要症状
        3. 可能病因
        4. 建议的检查项目
        5. 治疗建议
        6. 注意事项

        用清晰的结构和Markdown格式回复（支持加粗、列表等）。
        """

        headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer sk-xxxx"  # ⚠️ 建议改成环境变量读取
        }
        data = {
            "model": "deepseek-chat",
            "messages": [
                {"role": "system", "content": "你是专业医疗顾问，提供准确医学信息"},
                {"role": "user", "content": prompt}
            ],
            "stream": True
        }

        response = requests.post(
            "https://api.deepseek.com/v1/chat/completions",
            headers=headers,
            json=data,
            stream=True
        )

        if response.status_code != 200:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"AI接口调用失败: {response.text}"
            )

        full_ai_response = ""

        def generate():
            nonlocal full_ai_response
            for line in response.iter_lines():
                if line:
                    decoded_line = line.decode("utf-8")
                    if decoded_line.startswith("data: "):
                        data_str = decoded_line[6:]
                        if data_str == "[DONE]":
                            break
                        try:
                            data_json = json.loads(data_str)
                            delta = data_json["choices"][0]["delta"].get("content", "")
                            if delta:
                                full_ai_response += delta
                                yield delta
                        except (json.JSONDecodeError, KeyError):
                            continue

            # 保存对话到数据库
            try:
                conversation = [
                    {
                        "role": "user",
                        "content": query,
                        "time": datetime.now().strftime("%H:%M:%S")
                    },
                    {
                        "role": "ai",
                        "content": full_ai_response,
                        "time": datetime.now().strftime("%H:%M:%S")
                    }
                ]
                history = MedicalHistory(
                    user_id=current_user.id,
                    title=f"疾病查询: {query[:30]}",
                    content=json.dumps(conversation)
                )
                db.add(history)
                db.commit()
            except Exception as e:
                db.rollback()
                print(f"保存对话失败: {str(e)}")

        return Response(generate(), media_type="text/event-stream")

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"查询失败: {str(e)}"
        )



@router.post("/test-create", response_model=MedicalHistoryOut)
def test_create_medical_history(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """
    最小化测试接口：直接往数据库插一条固定数据
    """
    try:
        # 构造一条测试数据（注意 content 必须是合法 JSON 字符串）
        conversation = [
            {"role": "user", "content": "你好医生"},
            {"role": "ai", "content": "你好，请问有什么症状？"}
        ]

        history = MedicalHistory(
            user_id=current_user.id,
            title="测试会话",
            content=json.dumps(conversation)
        )

        db.add(history)
        db.commit()
        db.refresh(history)

        print(f"[INFO] 保存成功: id={history.id}, user_id={history.user_id}")
        return history

    except Exception as e:
        db.rollback()
        print(f"[ERROR] 保存失败: {e}")
        raise HTTPException(status_code=500, detail="数据库保存失败")

